<template>
    <div class="score">
        <div class="s-head">
            <svg class="icon" aria-hidden="true">
                <use xlink:href="#icon-iconNow"></use>
            </svg>
            <span>{{students.className}}，在读学生共
                <em>{{students.stuCount}}</em>人；已录
                <em>{{students.hasRecord}}</em>人，未录
                <em>{{students.stuCount-students.hasRecord}}</em>人</span>
            <span class="module-name">{{students.modelName}}</span>
        </div>
        <div class="s-body">
            <div class="s-left">
                <ul>
                    <li @click="studentClick(stuI)" v-for="(stu,stuI) in students.list" :class="{active:stu.isActive}">
                        <span>{{stu.stuName}}</span>
                        <div class="s-status" v-if="stu.recordStatus===1">
                            <img src="../../../assets/img/s-status.png" alt="">
                            <span class="lu" v-if="stu.status===0&&stu.isChanged!==1">录</span>
                            <span class="que" v-if="stu.status===1">缺</span>
                            <span class="huan" v-if="stu.status===0&&stu.isChanged===1">换</span>
                        </div>
                        <!--<svg v-if="stu.recordStatus===1&&stu.status===0&&stu.isChanged!==1" class="icon" aria-hidden="true">
                            <use xlink:href="#icon-gou"></use>
                        </svg>
                        <svg v-if="stu.recordStatus===1&&stu.status===1" class="icon quekao" aria-hidden="true">
                            <use xlink:href="#icon-quekao"></use>
                        </svg>
                        <svg v-if="stu.recordStatus===1&&stu.status===0&&stu.isChanged===1" class="icon huan" aria-hidden="true">
                            <use xlink:href="#icon-huan"></use>
                        </svg>-->
                    </li>
                </ul>
            </div>
            <div class="s-right">
                <div class="r-head">
                    <div class="exam-status">
                        <span class="es-lable">参考状态：</span>
                        <span class="es-btn" :class="{active:actStudent.status===0}" @click="examStatus(0)">参考</span>
                        <span class="es-btn" :class="{active:actStudent.status===1}" @click="examStatus(1)">缺考</span>
                    </div>
                    <div class="exam-change" @click="setScore">
                        <span v-if="actStudent.isChanged" class="using">该生使用试卷：{{actStudent.modelName}}</span>
                        <span>更换试卷</span>
                        <svg class="icon" aria-hidden="true">
                            <use xlink:href="#icon-genghuan"></use>
                        </svg>
                    </div>
                </div>
                <div class="exam-btn">
                    <span @click="resetScore(0)">全部零分</span>
                    <span @click="resetScore(100)">全部满分</span>
                    <span @click="resetScore('')">重置</span>
                </div>
                <div class="r-list">
                    <div class="l-head">
                        <div class="no">题目编号</div>
                        <div class="score">个人得分</div>
                        <div class="all-score">/满分值</div>
                    </div>
                    <div class="head-line"></div>
                    <ul v-for="(mod,modI) in actStudent.list" :class="{'last-ul':modI===actStudent.list.length-1}">
                        <span class="m-title">模块{{mod.sort | SectionToChinese}}{{mod.dataQuestionTypeName}}</span>
                        <li v-for="(que,queI) in mod.list" :class="{'is-empty':que.isEmpty}">
                            <div class="no">{{que.name}}</div>
                            <div class="score">
                                <el-input class="score-input" @keyup.native="keyEvent($event,que.sort)" placeholder="请输入分值" :disabled="!!actStudent.status" v-model="que.getScore" @blur="finishItem(que)"></el-input>
                            </div>
                            <div class="all-score">/{{que.score}}分</div>
                        </li>
                    </ul>
                    <div class="all-div">
                        试卷总分：{{actStudent.modelScore}} 分 ; 个人得分：
                        <em>{{allGetScore | formatNumber(2)}}</em> 分
                    </div>
                </div>
                <div class="save">
                    <el-button class="height-btn" type="primary" @click="saveScore" @focus.native="isFocused=true" @blur.native="isFocused=false">保存</el-button>
                </div>
            </div>
        </div>
        <select-module ref="sModule" type="change" @change="changeModule">
            <div class="current-module">当前模版：{{actStudent.moduleName||students.modelName}}</div>
        </select-module>
    </div>
</template>
<script>
import SelectModule from "./SelectModule"
import io from 'lib/io'
export default {
    components: {
        SelectModule
    },
    data() {
        return {
            classId: this.$route.query.classId,
            moduleId: this.$route.query.moduleId,
            students: {},
            actStudent: {},
            actIndex: 0,
            saving: false,
            isFocused: false
        }
    },
    computed: {
        allGetScore() {
            let score = 0
            this.actStudent.list && this.actStudent.list.map((item, i) => {
                item.list.map((que, queI) => {
                    score += Number(que.getScore)
                })
            })
            return score
        }
    },
    created() {
        this.getStudents()
    },
    mounted() {
        document.body.addEventListener('keydown', this.enter)
    },
    destroyed () {
      document.body.removeEventListener('keydown', this.enter)
    },
    methods: {
        enter(e){
            if (e.keyCode == '13') {
                if ((!this.saving) && (!this.isFocused)) {
                    this.saveScore()
                    this.saving = true
                    setTimeout(() => {
                        this.saving = false
                    }, 1000)
                }
            }
        },
        keyEvent(e, index) {
            let keyCode = window.event ? e.keyCode : e.which;
            switch (keyCode) {
                // case 13:
                //     this.saveScore()
                //     break
                case 38:
                    if (index > 1) {
                        this.setFocus(index - 2)
                    }
                    break
                case 40:
                    let actLength = this.actStudent.list && this.actStudent.list.length
                    let queLength = this.actStudent.list[actLength - 1].list.length
                    let no = this.actStudent.list[actLength - 1].list[queLength - 1].sort
                    if (index < no) {
                        this.setFocus(index)
                    }
                    break
            }
        },
        setFocus(index) {
            document.getElementsByClassName('score-input')[index].querySelector('input').focus()
        },
        async changeModule(row) {
            // 该学生在班级内同一个活动是否存在录分数据
            let { data } = await io.post6(io.isExist, { stuId: this.actStudent.stuId, modelId: row.id, classId: this.students.classId })
            if (data.success) {
                if (data.data.isExist === 1) {
                    this.$confirm('该学生分数已录入其他试卷，确认更换？保存后覆盖已录入分数！', '提示').then(() => {
                        this.changing(row)
                    }).catch((err) => {
                        console.log(err)
                    })
                } else {
                    this.changing(row)
                }
            }

        },
        async changing(row) {
            let { data } = await io.post6(io.detailExamModelChange, { id: row.id, stuId: this.actStudent.stuId })
            if (data.success) {
                let stu = { ...data.data, moduleName: row.name, stuName: this.actStudent.stuName, status: 0, isActive: this.actStudent.isActive, modelId: row.id }
                this.actStudent = { ...stu }
                this.students.list[this.actIndex] = { ...stu }
                this.$refs.sModule.changeStatus(false)
            }
        },
        setScore() {
            let row = { id: this.students.classId, baseLevelId: this.students.levelId, activeId: this.students.activityId }
            this.$refs.sModule.getActiveList(row)
        },
        examStatus(status) {
            this.students.list[this.actIndex].status = status
            this.actStudent.status = status
        },
        resetScore(score) {
            this.actStudent.list.map((mod, modI) => {
                mod.list.map((que, queI) => {
                    if (score === 100) {
                        que.getScore = que.score
                    } else {
                        que.getScore = score
                    }
                })
            })
        },
        finishItem(que) {
            if (que.getScore !== '') {
                que.isEmpty = false
            }
            let check = /^\d+(\.{0,1}\d+){0,1}$/;
            if (que.getScore && !check.test(que.getScore)) {
                que.getScore = ''
                this.$message('分数只能是非负数')
                return
            }
            if (que.getScore > que.score) {
                que.getScore = ''
                this.$message('个人得分不能大于满分')
                return
            }
            let numArr = String(que.getScore).split('.')
            if (que.getScore < 0 || numArr[1] && numArr[1].length > 2) {
                que.getScore = ''
                this.$message('分数只能为大于等于0的正数，且小数点最多2位')
            }
        },
        async getStudents() {
            let { data } = await io.post6(io.getStudents, { classId: this.classId, modelId: this.moduleId })
            if (data.success) {
                let hasRecord = 0
                data.data.list.map((stu, stuI) => {
                    if (stu.recordStatus === 1) {
                        hasRecord++
                    } else {
                        stu.list.map((mod, modI) => {
                            mod.list.map((que, queI) => {
                                que.getScore = ''
                                que.isEmpty = false
                            })
                        })
                    }
                    this.actStudent = data.data.list[0]
                    stuI === 0 ? stu.isActive = true : stu.isActive = false
                    stu.status === null ? stu.status = 0 : ''
                })
                data.data.hasRecord = hasRecord
                this.students = data.data
                this.$nextTick().then(() => {
                    this.setFocus(0)
                })
            }
        },
        // 保存分数
        async saveScore() {
            if (this.saving) {
                return
            }
            let scores = []
            console.log('x',this.actStudent)
            if (this.actStudent.status === 0) {
                // 遍历所有学生，判断是否为空，把空的编号放入emptyNo，否则就把分数放入scores数组
                console.log(1,emptyNo)
                let emptyNo = []
                this.actStudent.list.map((mod, modI) => {
                    mod.list.map((que, queI) => {
                        if (que.getScore === '') {
                            emptyNo.push(que.sort)
                            que.isEmpty = true
                        } else {
                            que.isEmpty = false
                        }
                        scores.push(que.getScore)
                    })
                })
                console.log(2,emptyNo)
                if (emptyNo.length) {
                    console.log("xxxddd")
                    this.$message(`第${emptyNo.join(',')}题的分数未输入`)
                    return
                }
            }
            let params = {
                stuId: this.actStudent.stuId,
                modelId: this.actStudent.modelId || this.students.modelId,
                classId: this.students.classId,
                status: this.actStudent.status,
                scores: scores.join(',')
            }
            let { data } = await io.post6(io.record, params)
            if (data.success) {
                this.afterSave()
            }
        },
        // 保存后重新计算页面的统计数据，并判断下一步行为
        afterSave() {
            this.students.list[this.actIndex].recordStatus === 1 ? '' : this.students.hasRecord++
            this.actStudent.recordStatus = 1
            this.students.list[this.actIndex].recordStatus = 1
            this.students.list[this.actIndex].isActive = false
            let nextIndex = null
            this.students.list.map((stu, stuI) => {
                if (stu.recordStatus === 0 && nextIndex === null) {
                    nextIndex = stuI
                }
            })
            if (nextIndex === null) {
                this.$confirm('已经是最后一个，是否离开？', {
                    confirmButtonText: '离开',
                    cancelButtonText: '留在本页',
                }).then(() => {
                    this.$router.go(-1)
                }).catch((err) => {
                    console.log(err)
                })
            } else {
                this.studentClick(nextIndex)
            }
        },
        // 学生名字单击事件
        studentClick(index) {
            this.students.list.map((stu) => {
                stu.isActive = false
            })
            this.actStudent = this.students.list[index]
            this.actStudent.isActive = true
            this.actIndex = index
            this.$nextTick().then(() => {
                this.setFocus(0)
            })
        }
    }
}
</script>

<style lang="stylus" scoped>
.score
    color #333333
    font-size 14px
    .s-head,.s-body
        width 980px
        em
            font-style normal
            color #ff9000
            font-weight bold
            margin 0 5px
    .s-head
        height 46px
        line-height 46px
        padding-left 15px
        box-sizing border-box
        .icon
            color #009ada
        .module-name
            float right
    .s-body
        padding-bottom 20px
        .s-left
            width 130px
            display inline-block
            margin-right 4px
            vertical-align top
            .huan
                color #2aa946
            .quekao
                color #00b1d1
                font-size 84px !important
                top: 2px !important;
                right: -24px !important;
            li
                cursor pointer
                height 40px
                line-height 40px
                background-color #ddeaee
                margin-bottom 4px
                text-align center
                position relative
                &.active
                    background #c9efe6
                    font-weight bold
                .icon
                    position absolute
                    right 6px
                    font-size 26px
                    top 6px
                .s-status
                    position absolute
                    right 6px
                    top 0
                    span
                        position absolute
                        display inline-block
                        height 30px
                        top 0
                        line-height 26px
                        left 7px
                        font-size 12px
                        font-weight bold
                        &.lu
                            color #FF9000
                        &.que
                            color #2EB9EA
                        &.huan
                            color #36D88E

        .s-right
            width 838px
            display inline-block
            border 1px dashed #c9efe6
            vertical-align top
            .r-head
                height 50px
                background #c9efe6
                align-items center
                font-weight bold
                padding-top 2px
                box-sizing border-box
                .el-radio
                    font-weight bold
                    color #333333
                .exam-change
                    width 50%
                    display inline-block
                    color #009ada
                    text-align right
                    .using
                        color #ff9000
                        margin-right 10px
                    .icon
                        font-size 23px
                        cursor pointer
                        margin-right 10px
                    span
                        position relative
                        cursor pointer
                        top -2px
                        left -4px
                .exam-status
                    width 49%
                    display inline-block
                    margin-top 2px
                    .es-btn
                        margin-right 20px
                        border-radius 4px
                        display inline-block
                        height 38px
                        width 100px
                        border 1px solid #01cdbe
                        text-align center
                        line-height 40px
                        cursor pointer
                        &.active
                            background #01cdbe
                            color #fff
                            border-color #01cdbe
                    .es-lable
                        margin-left 38px
            .exam-btn
                flex 1
                text-align center
                margin-top 20px
                span
                    display inline-block
                    width 100px
                    height 34px
                    text-align center
                    line-height 34px
                    border 1px solid #009ada
                    border-radius 4px
                    font-weight bold
                    color #009ada
                    margin-right 180px
                    cursor pointer
                    &:last-child
                        margin-right 10px
            .r-list
                width 654px
                margin auto
                .l-head
                    display flex
                    height 52px
                    font-weight bold
                    margin-top 8px
                .head-line
                    width 654px
                    height 3px
                    background-image linear-gradient(90deg, #009fd7 0%, #01d1bb 100%)
                    .score
                        padding-right 26px
                        width 174px
                .no
                    width 280px
                    display inline-block
                    text-align center
                    line-height 52px
                .score
                    width 200px
                    display inline-block
                    text-align right
                    line-height 52px
                .all-score
                    width 160px
                    display inline-block
                    line-height 52px
                    padding-left 10px
                    box-sizing border-box
                ul
                    border-bottom 3px solid #c9efe6
                    padding-bottom 20px
                    position relative
                    min-height 90px
                    &.last-ul
                        border-bottom 0 !important
                        padding-bottom 0
                    .m-title
                        display inline-block
                        position absolute
                        left -32px
                        width 20px
                        height auto
                        top -4px
                        &:after
                            content ''
                            width 0
                            height 0
                            border-left 8px solid #c9efe6
                            border-top 9px solid transparent
                            border-bottom 9px solid transparent
                            position absolute
                            top 0
                            right -8px
                    li
                        height 60px
                        border-bottom 1px dashed #23c9b3
                        line-height 60px
                        &.is-empty
                            background red
                        &:last-child
                            border-bottom 0
                        .el-input
                            width 108px
                .all-div
                    border-top 1px dashed #23c9b3
                    padding 10px 0
                    text-align right
        .save
            text-align center
            padding 30px 0
.current-module
    margin-top 10px
    padding 10px 0
</style>

